<?php

declare (strict_types = 1);

namespace app\mini\controller;

use app\admin\model\Setting;

use app\BaseController;

use app\crm\model\Customer;
use app\mini\model\CustomerPointLogModel;
use app\mini\model\CustomerPointModel;
use think\facade\Cache;

use think\response\Json;

use think\facade\Session;

use app\mini\model\MiniProgramFans;

use think\facade\Db;

use app\admin\model\Access;

use app\Jwt;

/*

* 小程序用户登录

*/

class Login extends BaseController

{

//   public function handleLogin111()

//   {

//     $param = $this->request->only(['code'=>'']);

//     // $code = $param['code'];

//     // $phone = $param['phone'];

//     // $nickName = $param['nickName'];

//     // $telephone = $param['telephone'];



//     if( empty($code) ){

//       return resultArray(['error' => '参数错误']);

//     }

//     /*通过code换取session_key openid*/

//     $requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

//     $requestUrl = sprintf($requestUrl,MiniProgramConfig::$AppID,MiniProgramConfig::$AppSecret,$code);

//     $response = $this->getCurl($requestUrl);

//     if( isset($response['errcode']) ){

//       return resultArray(['error' => $response['errmsg'] ]);

//     }

//     /*添加到库*/

//     $data['openid'] = $param['openid'];

//     $data['phone'] = $param['phone'];

//     $data['nickName'] = $param['nickName'];

//     $data['telephone'] = $param['telephone'];

//     $fansId = \app\mini\model\MiniProgramFans::findOrCreat($param['openid'],$data);  //返回粉丝主键ID

//     /*生成token 存储用户信息*/

//     $token = \app\Jwt::getToken(['fansId'=>$fansId]);

//     /*保存缓存信息*/

//     $oldData = (array) Cache::get('mfans:MiniProgram-'.$fansId);

//     Cache::set('mfans:MiniProgram-'.$fansId,array_merge($oldData,[

//       'fansId'      =>  $fansId,

//       'sessionKey'  =>  $response['session_key'],

//       'openId'      =>  $response['openid'],

//       'token'       =>  $token

//     ]));

//     $data['token'] = $token;

//     $customer_id = 0;

//     $info =  Cache::get('mfans:MiniProgram-'.$fansId);

//     if( empty($info) ){

//       $info = MiniProgramFans::where('id','=',$fansId)

//                     ->field('id as fansId,openId,nickName,gender,city,province,country,avatarUrl,customerId,telephone')

//                     ->find();

//       if( is_null($info) ){

//         $info = [];

//       }else{

//         $info = $info->toArray();

//       }

//       $scode = ''; // 初始化签约码

//       if( $info['customerId'] != 0 ){

//         $scode = \app\crm\model\Customer::where('customer_id','=',$info['customerId'])->value('sign_up_number','');

//       }

//       Cache::set('mfans:MiniProgram-'.$this->fansId,$info);

//       $customer_id = $info['customerId'];

//     }else{



//     }

//     // return $info;

//     $data['customer_id'] = $customer_id;

//     // $data['customer_id'] = 28;

//     return resultArray(['error' => '获取成功','data'=>$data]);

//   }



  /*curl Get请求*/

  protected function getCurl($url)

  {

    $headerArray =array("Content-type:application/json;","Accept:application/json");

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);

    $output = curl_exec($curl);

    curl_close($curl);

    $output = json_decode($output,true);

    return $output;

  }



  /*curl POST请求*/

  protected function postCurl($url,$data)

  {

    $data  = json_encode($data);

    $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);

    curl_setopt($curl, CURLOPT_POST, 1);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $output = curl_exec($curl);

    curl_close($curl);

    $output = json_decode($output,true);

    return $output;

  }



  /**

     * 小程序基础配置

     * @param  Setting $setting

     * @return Json

     * @author Mr.Liu Wuchen

     * @create 2021-08-28 15:21

     */

    public function loginLogo(Setting $setting): Json

    {

        $request['group'] = 'min_basis';

        $request['name']  = ['login_logo'];

        $data = $setting->getDataInfo($request);

        if (!$data) {

            return resultArray(['error' => $setting->getError()]);

        }

        return resultArray(['error' => $setting->getError(), 'data' => $data]);

    }



    public function loginYg(): Json

    {

        $param      = $this->request->param();

        $phone      = $param['phone'] ?? '';

        $password   = $param['password'] ?? "";

        $loginType  = $param['type'] ?? "3";

        if(empty($phone)){

            return resultArray(['error' => '手机号不能为空']);

        }

        if(empty($password)){

            return resultArray(['error' => '密码不能为空']);

        }

        // $map = array();

        // $map['phone'] = $phone;

        // $userInfo = Db::name('shop_person')->where($map)->field('id,shop_id,shop_name,name,phone')->find();

        // if(!$userInfo){

        //     return resultArray(['error' => '当前账号不存在']);

        // }

        $auWhere = [];

        array_push($auWhere,['username','=',$phone]);

        array_push($auWhere,['type','=',$loginType]);

        array_push($auWhere,['status','=',1]);

        array_push($auWhere,['is_status','=',0]);

        // array_push($auWhere,['type','=',3]);

        // echo "<pre>";
        // print_r($auWhere);
        // echo "</pre>";
        // exit;



        $authInfo = Db::name('admin_user')->where($auWhere)->field('id,shop_id,shop_person_id,salt,username,password,sex,type,realname,group_id')->order('id asc')->find();

        // echo "<pre>";
        // print_r($authInfo);
        // echo "</pre>";
        // exit;


        if(!$authInfo){

            return resultArray(['error' => '当前账号不存在']);

        }

        // if(!$authInfo['shop_id']){

        //     return resultArray(['error' => '账号类型错误']);

        // }

        if (user_md5($password, $authInfo['salt'], $authInfo['username']) !== $authInfo['password']) {

            return resultArray(['error' => '密码错误']);

        }

        if($authInfo['type'] == 3){
            $userInfo = Db::name('shop_person')->where('id','=',$authInfo['shop_person_id'])->field('id,shop_id,shop_name,name,phone,station_name,position_id')->find();

            if(empty($userInfo)){

                return resultArray(['error' => '员工信息不存在']);

            }
        }else{

            $groupInfo = Db::name('admin_group')->where('id','=',$authInfo['group_id'])->field('title')->find(); // 登陆人角色

            $dataAuth = Db::name('admin_data_auth')->where('group_id','=',$authInfo['group_id'])->field('market')->find(); // 登陆门店权限

            $userInfo['name'] = $authInfo['realname'];
            $userInfo['phone'] = $authInfo['username'];
            $userInfo['station_name'] = $groupInfo['title'];
            $userInfo['shopIds'] = $dataAuth['market'];
            $userInfo['position_id'] = '';
        }

        // echo "<pre>";
        // print_r($userInfo);
        // echo "</pre>";
        // exit;



        $userInfo['sex'] = $authInfo['sex'];
        // Session::set('user_id', $authInfo['id']);
        if(empty($userInfo['shopIds'])){
            $shopIds = $this->getCommonShopIdsCollectByUserType($authInfo);
            $userInfo['shopIds'] = $shopIds;
        }else{
            $shopIds = json_decode($userInfo['shopIds'],true);
        }


        $userInfo['user_id'] = $authInfo['id'];

        $where = [];

        array_push($where,['shop_id','in',$shopIds]);

        array_push($where,['status','=','1']);

        array_push($where,['type','<>','2']);

        $shopList = Db::name('shop')->where($where)->column('shop_id,shop_name');

        $userInfo['shopList'] = $shopList;

        return resultArray(['error' => '', 'data' => $userInfo]);

    }

    public function getCommonShopIdsCollectByUserType($userInfo)
    {
        switch ($userInfo['type']) {
            case 1:
                $accessModel = new Access();
                $dataAuth =$accessModel->getCommonUserDataAuth($userInfo['id']);
                $shopIds =$dataAuth['market']??[];
                break;
            default:
                $relationShop =Db::name('shop')->where('shop_id',$userInfo['shop_id'])->value('relation_shop');
                if($relationShop != "null" && !empty($relationShop)){
                    $relationShop =json_decode($relationShop,true);
                    $shopIds =array_merge($relationShop,[$userInfo['shop_id']]);
                }else{
                    $shopIds=[$userInfo['shop_id']];
                }
                $shopIds =$userInfo['shop_id']?$shopIds:[];
                break;
        }
        return $shopIds;
    }



    public function loginYgd(): Json

    {

        $param      = $this->request->param();

        $phone      = $param['phone'] ?? '';

        $code   = $param['code'] ?? "";

        if(empty($phone)){

            return resultArray(['error' => '手机号不能为空']);

        }

        if(empty($code)){

            return resultArray(['error' => '验证码不能为空']);

        }

        $map = array();

        $map['phone'] = $phone;

        $userInfo = Db::name('shop_person')->where($map)->field('id,shop_id,shop_name,name')->find();

        if(!$userInfo){

            return resultArray(['error' => '当前账号不存在']);

        }

        $where = [];

        $time  = time()-15*60;



        array_push($where,['code','=',$code]);

        array_push($where,['phone','=',$phone]);

        array_push($where,['type','=',$time]);

        array_push($where,['create_time','>=',$time]);

        $res = Db::name('phone_code')->where($where)->find();

        if (!$res) {

          return resultArray(['error' => '验证码错误']);

        }

        // if (user_md5($password, $userInfo['salt'], $userInfo['username']) !== $userInfo['password']) {

        //     return resultArray(['error' => '密码错误']);

        // }



        return resultArray(['error' => '', 'data' => $userInfo]);

    }





    ///重新登录

    	/**

	 * 用户登录

	 * @param LoginService $loginService

	 * @return Json

	 * @throws \Exception

	 * @author sl

	 * @create 2021-12-24 14:07

	 */

	public function handleLogin(): Json

	{

	   // $this->param      = $this->request->param();

		$this->param = $this->request->only(['code','tel_encrypted','tel_iv', 'fans_encrypted','fans_iv','turn_id',]);

		$this->app_id     = MiniProgramConfig::$AppID;

		$this->app_secret = MiniProgramConfig::$AppSecret;

// 		print_r($this->app_id);

// 		print_r($this->app_secret);

// 		exit;

		$request = $this->param;

		$phone = '';

		$customer_id = 0;

		try {

            $code               = $request['code'] ?? '';

            $telEncryptedData   = $request['tel_encrypted'] ?? '';

            $telIv              = $request['tel_iv'] ?? '';

            $fansEncryptedData  = $request['fans_encrypted'] ?? '';

            $fansIv             = $request['fans_iv'] ?? '';

            $turn_id            = $request['turn_id']??'';

            if(!$code || !$telEncryptedData || !$telIv || !$fansEncryptedData || !$fansIv)

            {

                return resultArray(['error' => '参数错误', 'code' => 401]);

            }



            // 通过code获取session_key、openid

            $requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

            // print_r($code);exit;

            $requestUrl = sprintf($requestUrl, $this->app_id, $this->app_secret, $code);

            $response   = $this->getCurl($requestUrl);

            // print_r($response);exit;

            if(isset($response['errcode']))

            {

                return resultArray(['error' => $response['errmsg'], 'code' => 401]);

            }

            $openid      = $response['openid'] ?? '';

            $unionid     = $response['unionid'] ?? '';

            $session_key = $response['session_key'] ?? '';



            // 通过encryptedData、iv、session_key获取用户手机号

            $telRes = $this->decryptData($telEncryptedData, $telIv, $session_key, $tel_data);

            if(!$telRes)

            {

                return resultArray(['error' => '获取手机号失败，请重试！', 'code' => 401]);

            }



            // 通过encryptedData、iv、session_key获取用户信息

            $fansRes = $this->decryptData($fansEncryptedData, $fansIv, $session_key, $fans_data);

            if(!$fansRes)

            {

                return resultArray(['error' => '获取用户信息失败，请重试！', 'code' => 401]);

            }

            // 查询用户是否已注册

            $field = ['id'];

            $fansInfo = Db::name('mini_program_fans')->where('openid', '=', $openid)->field($field)->find();

            // $fansInfo = MiniProgramFans::find(['openid' => $openid], $field);

            // if(!$fansInfo)

            // {

            //     return resultArray(['error' => '获取用户信息失败，请重试！', 'code' => 401]);

            // }




            $data = [];

            $data['openId']     = $openid ?? '';

            $data['unionId']     = $unionid ?? '';

            $data['nickName']   = $fans_data['nickName'] ?? '';

            $data['gender']     = $fans_data['gender'] ?? 0;

            $data['country']    = $fans_data['country'] ?? 0;

            $data['province']   = $fans_data['province'] ?? 0;

            $data['city']       = $fans_data['city'] ?? 0;

            $data['avatarUrl']  = $fans_data['avatarUrl'] ?? '';

            $data['telephone']  = $tel_data['phoneNumber'] ?? '';

            $data['update_time']= date('Y-m-d H:i:s');

            $phone = $data['telephone'];

            // $customer_id = Db::name('customer')->where('telephone','=',$phone)->value('id') ?? 0;
           
            $customer_ids = Db::name('customer')->where('telephone','=',$phone)->column('id,shop_id,fcustId');
           
            
            if(!$customer_ids){
                if(!$turn_id)
                {
                    return resultArray(['error' => '您当前登录的手机号暂未注册！', 'code' => 401]);
                }else{

                }
            }

           
            $shop_ids = array_values(array_unique(array_column($customer_ids,'shop_id')))??[];

            $shop_type = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_type','shop_id');

            $cs_tel = [18668918959,15617433765,15838013986]; // 门诊测试顾客手机号
            
            if(in_array($phone,$cs_tel)){
                foreach ($customer_ids as $key => $value) {

                    if($shop_type[$value['shop_id']] == '1'){
    
                        $customer_id = $value['id'];
                    }
                }
            }else{
                foreach ($customer_ids as $key => $value) {

                    // if($shop_type[$value['shop_id']] == '2'){
                     
                        $customer_id = $value['id'];
    
                    // }
    
                }
            }

            if($phone == '15838013986'){
                echo $customer_id;
                exit;
            }


            if($customer_id == '0'){
                if(!empty($turn_id))//通过转介绍进入小程序的客户注册一个空门店客户记录。
                {
                    $customer_id=$this->turnNewCustomer($tel_data['phoneNumber'],$turn_id);

                    if($customer_id == '0')
                    {
                        return resultArray(['error' => '您当前登录的手机号暂未在门店注册！', 'code' => 401]);
                    }
                }

            }




            // echo "<pre>";
            // print_r($customer_ids);
            // echo "</pre>";
            // exit;

            $data['customerId']= $customer_id;


            // 已注册，更新用户数据；未注册，插入用户数据

            if($fansInfo)

            {

                $fansId = $fansInfo['id'];

                $updateRes = Db::name('mini_program_fans')->where('id', '=', $fansId)->update($data);

            }

            else{

                $data['create_time'] = date('Y-m-d H:i:s');

                $fansId = Db::name('mini_program_fans')->insertGetId($data);

            }



            // 生成token

            $token = Jwt::getToken(['fansId' => $fansId]);



            // 缓存或更新用户信息

            $oldFansInfo = (array) Cache::get('cmfans:MiniProgram-'.$fansId);

            $newFansInfo =

            Cache::set('cmfans:MiniProgram-'.$fansId,array_merge($oldFansInfo,[

                'fansId'      =>  $fansId ?? 0,

                'sessionKey'  =>  $session_key ?? '',

                'openId'      =>  $openid ?? '',

                'token'       =>  $token,

                'telephone'   =>  $tel_data['phoneNumber'] ?? '',

                'nickName'    =>  $fans_data['nickName'] ?? '',

                'gender'      =>  $fans_data['gender'] ?? 0,

                'city'        =>  $fans_data['city'] ?? 0,

                'province'    =>  $fans_data['province'] ?? 0,

                'country'     =>  $fans_data['country'] ?? 0,

                'avatarUrl'   =>  $fans_data['avatarUrl'] ?? '',

            ]));



        } catch (\Exception $e) {

            throw new \Exception($e->getMessage(), $e->getCode());

        }



       

        $fieldArr = ['id', 'nickName', 'gender', 'country', 'province', 'city', 'avatarUrl', 'telephone', 'create_time'];

        // $return = MiniProgramFans::find(['id' => $fansId], $fieldArr)->toArray();
        $return = [];
        $return = Db::name('mini_program_fans')->where('id', '=', $fansId)->find();
         
        $return['token'] = $token;

        $return['customer_id'] = $customer_id;


		if (!$return){

			return resultArray(['error' => '登录失败', 'code' => 400]);

		}

		return resultArray(['error' => '登录成功', 'data' => $return]);

	}



	 /**

     * 解密

     * error code 说明.

     * <ul>

     *    <li>-41001: encodingAesKey 非法</li>

     *    <li>-41003: aes 解密失败</li>

     *    <li>-41004: 解密后得到的buffer非法</li>

     *    <li>-41005: base64加密失败</li>

     *    <li>-41016: base64解密失败</li>

     * </ul>

     */

    protected function decryptData( $encryptedData, $iv, $sessionKey, &$data )

    {

        if (strlen($sessionKey) != 24)

        {

            // echo "1";exit;
            // return -41001;

            return false;

        }

        $aesKey=base64_decode($sessionKey);



        if (strlen($iv) != 24)

        {

            // echo "2";exit;
            // return -41002;

            return false;

        }

        $aesIV=base64_decode($iv);



        $aesCipher=base64_decode($encryptedData);

        $result= openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        if( is_bool($result) )

        {
            // echo "3";exit;

            // return -41016;

            return false;

        }

        $dataObj= json_decode( $result);

        if( $dataObj  == NULL )

        {
            // echo "4";exit;

            // return -41003;

            return false;

        }

        if( $dataObj->watermark->appid != $this->app_id )

        {
            // echo "5";exit;

            // return -41003;

            return false;

        }

        $data = json_decode( $result,true);

        return true;

    }

    /**
     * 添加转介绍新客户
     * @param $telephone
     * @param $tureCustomerId
     * @return string
     */
    public function turnNewCustomer($telephone,$tureCustomerId)
    {
        $data = [
            'telephone'=>$telephone,
            'turn_id'=>$tureCustomerId,
            'customer_name'=>"微信用户",
            'shop_id'=>74076159037951,
            'source_id'=>47,
            'repair_progress'=>57,
            'status'=>1,
            'create_time'           => time(),
            'update_time'           => time()
        ];

        $newCustomer = new Customer();
//        $turnCostomer = Customer::find($tureCustomerId);
//        if($turnCostomer)
//        {
//            $data['shop_id'] = $turnCostomer->shop_id;
//        }
        $customerId = $newCustomer->insertGetId($data);
        if ($customerId) {
            $customer_balanceAll = [
                [
                    'shop_id'       => 74076159037951,
                    'customer_id'   => $customerId,
                    'balance_category_id'   => 1,
                ],[
                    'shop_id'       => 74076159037951,
                    'customer_id'   => $customerId,
                    'balance_category_id'   => 2,
                ]
            ];
            $res = Db::name('customer_balance')->where('customer_id','=',$customerId)->select()->toArray();
            if(!$res){
                Db::name('customer_balance')->insertAll($customer_balanceAll);
            }
            $this->error = '添加成功';
//            CustomerPointModel::pointChange($tureCustomerId,4);
            return $customerId;
        }else{
            return '0';
        }
    }

    /**
     * 编辑信息
     *
     * @return Json
     */
    public function editPersonInfo()
    {
        $this->param = $this->request->only(['customer_id','name','sex', 'birth',]);
        $request = $this->param;
        $customer = Customer::find($request['customer_id']);
        if(empty($customer))
        {
            return resultArray(['error' => '未找到该用户', 'code' => 400]);
        }
        $customer->customer_name=$request['name']??'';
        $customer->sex=$request['sex']??'';
        $customer->birthday=strtotime($request['birth'])??0;
        $res = $customer->save();
        $existLog = CustomerPointLogModel::where([['origin_id','=',11],['customer_id','=',$request['customer_id']]])->find();//如果已经有过完善信息记录，则不会再给分
        if($res)
        {
            if(!$existLog)
            {
                if(!empty($customer->turn_id))
                {
                    CustomerPointModel::pointChange($customer->turn_id,4);
                }

                CustomerPointModel::pointChange($request['customer_id'],11);
            }
            return $this->success([],'编辑完成');
        }else{
            return $this->failed(400, "编辑失败");

        }

    }
//    public function test()
//    {
//        $request = request()->param();
//        return $this->turnNewCustomer($request['telephone'],$request['turn_id']);
//    }

}

